package com.woniu.adapter;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.outlet.dao.CustomerPoMapper;
import com.woniu.outlet.po.CustomerPo;
import com.woniu.outlet.rabbitmq.MessageRepo;
import com.woniu.outlet.redis.RedisRepo;
import com.woniu.utils.SnowflakeIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class CustomerAdapter {

    @Autowired
    private CustomerPoMapper customerPoMapper;

    @Autowired
    private RedisRepo redisRepo;

    @Autowired
    private MessageRepo messageRepo;


    public List<CustomerPo> findCustomers() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String str = redisRepo.findRedisRepo("customer:list");
        List<CustomerPo> lists = new ArrayList<>();
        if (!StringUtils.isEmpty(str)) {
            lists = mapper.readValue(str, new TypeReference<List<CustomerPo>>() {
            });
            return lists;
        }
        lists = customerPoMapper.selectByExample(null);
        //存到redis
        redisRepo.saveRedisRepo("customer:list",mapper.writeValueAsString(lists));
        return lists;
    }

    public CustomerPo getCustomerById(Long id) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String str = redisRepo.findRedisRepo("customer:" + id);
        CustomerPo customerPo = null;
        if (!StringUtils.isEmpty(str)) {
            customerPo = mapper.readValue(str, new TypeReference<CustomerPo>() {
            });
            return customerPo;
        }
        customerPo = customerPoMapper.selectByPrimaryKey(id);
        //存到redis
        redisRepo.saveRedisRepo("customer:"+id,mapper.writeValueAsString(customerPo));
        return customerPo;
    }

    public void addCustomerPo(CustomerPo customerPo){
        SnowflakeIdGenerator snowflakeIdGenerator = new SnowflakeIdGenerator();
        long id = snowflakeIdGenerator.nextId();
        customerPo.setCustomerCode("KHBM"+id);
        customerPoMapper.insert(customerPo);
        redisRepo.deleteRedisRepo("customer:list");

    }

    public void updateCustomerPo(CustomerPo customerPo){
        customerPoMapper.updateByPrimaryKeySelective(customerPo);
        redisRepo.deleteRedisRepo("customer:list");
    }

    public void deleteCustomerPoById(Long id){
        customerPoMapper.deleteByPrimaryKey(id);
        redisRepo.deleteRedisRepo("customer:list");
    }
}
